import axios from 'axios'

import { ElMessage } from 'element-plus'
//引入用户相关的仓库
import useUserStore from '@/stores/modules/user'
const baseURL = import.meta.env.VITE_APP_BASE_API

const timeout = 5000

const service = axios.create({
  baseURL,
  timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    //获取用户相关的小仓库:获取仓库内部token,登录成功以后携带给服务器
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers['Authorization'] = `Bearer ${userStore.token}`
    }
    return config
  },
  (error) => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res.code !== 20000) {
      ElMessage({
        message: res.message || 'Error',
        type: 'error',
        duration: 3 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  (error) => {
    console.log('error.response: ', error.response)
    ElMessage({
      message: error?.response?.data?.message || '传参错误',
      type: 'error',
      duration: 1000
    })
    return Promise.reject(error)
  }
)

export default service
